<template>
  <view class="body">
    <!-- 轮播图部分 -->
    <swiper autoplay="true" interval="3000" circular="true" indicator-dots="true">
      <swiper-item v-for="(item, index) in swiperList" :key="index">
        <image class="banner-item" :src="item.image" @click="playVideo(item)" lazy-load :lazy-load-margin="0" />
      </swiper-item>
    </swiper>
    <!-- 广播 -->
    <view class="broadcast">
      <view class="broadcast-content">
        <image class="broadcast-image" src="/static/image/喇叭.png" lazy-load />
        <text class="broadcast-text">{{ broadcasts }}</text>
      </view>
    </view>
    <!-- 更多商品 -->
    <!--    <view class="more" @click="goToMoreProduct">更多商品</view> -->
    <!-- 商品类别 -->
    <!-- <view class="category-list">
      <view class="category-item" v-for="(item, index) in categoryList" :key="index" @click="goToCategory(index)">
        <image class="category-image" :src="item.LXimages||'https://shop.flowergk.com/images/20240826192859.jpg'"
          lazy-load :lazy-load-margin="0" />
        <text class="category-LXName">{{ item.LXName }}</text>
      </view>
    </view> -->
    <!-- 商品列表部分 -->
    <!-- 等级(1为甄选，2优选，3为一级品，4为2二级品，5为三级品) -->
    <view class="product-list">
      <view v-for="(item, index) in productList" :key="index" class="product-item" @click="goToProductDetail(item)">

        <view class="product-image-wrapper">
          <image :src="item.image" class="product-image" lazy-load :lazy-load-margin="0" />
          <view v-if="item.inventory <= 0" class="sold-out-overlay">已售罄</view>
        </view>
        <view class="product-info">
          <text class="product-title">{{ item.goodsName }}</text>
          <!-- <text class="product-title">{{ this.grade(item.grade) }} {{ item.goodsName }}</text> -->
          <text class="product-content">{{ item.details }}</text>

          <view class="price-cart">
            <view class="price-buttom">
              <text class="proudct-sales">销量:{{ item.sales }}</text>
              <!-- Display both the regular price and member price -->
              <!-- <text class="product-price">¥{{ item.money }} 会员价:¥{{ item.userMoney }}</text> -->
              <text class="product-price">¥{{ item.money }}</text>
            </view>

            <button :class="['cart-button', item.inventory <= 0 ? 'disabled' : '']" @click.stop="addToCart(item)">
              加入购物车
            </button>
          </view>
        </view>
      </view>
    </view>


    <!-- 视频播放器部分，隐藏或显示 -->
    <view v-if="isVideoPlaying" class="video-container">
      <video id="myVideo" :src="mp4Url" controls autoplay @ended="onVideoEnd" style="width: 100%; height: 100%"></video>
      <view class="close-button" @click="closeVideo">X</view>
    </view>
    <!-- <view class="bottom-tabbar">
      <navigator url="/pages/index/index">
        <view class="tabbar-item">
          <image src="../../static/tabbar/客服.png" mode="" />
          <text>客服</text>
        </view>
      </navigator>
      <navigator url="/pages/order/order">
        <view class="tabbar-item">
          <image src="../../static/tabbar/订单.png" mode="" />
          <text>订单</text>
        </view>
      </navigator>
      <navigator url="/pages/shoppingCart/shoppingCart">
        <view class="tabbar-item shoppingCart">
          <image src="../../static/tabbar/购物车满.png" mode="" />
          <text>购物车</text>
          <view v-if="cartItemCount > 0" class="cart-badge">{{ cartItemCount }}</view>
        </view>
      </navigator>
    </view> -->
  </view>
</template>

<script>
  import {
    getbroadcast,
    getGoodsInfo,
    getGoodslx
  } from "../../api/goods/goods";
  import {
    InsertFootPrint
  } from "../../api/footprint/footprint.js";
  import {
    getCarousel
  } from "../../api/swiper/swiper.js";

  export default {
    data() {
      return {
        // scene: '',
        productList: [],
        swiperList: [],
        mp4Url: "",
        isVideoPlaying: false, // 控制视频的显示状态
        cartItemCount: 0, // 购物车数量
        categoryList: [],
        broadcasts: [],
        currentBroadcastIndex: 0,
        broadcastIntervalId: null,
        userId: '',
      };
    },
    computed: {
      currentBroadcast() {
        return this.broadcasts[this.currentBroadcastIndex];
      },
    },
    onShow() {
      this.getOpenid();
      this.getGoodslx();
      this.getbroadcast();
    },
    onLoad() {
      this.getUserInfo();
      this.toLogin();
      this.getGoodsInfo();
      this.getCarousel();
      this.startBroadcast();

      // this.scene = options.scene
      // //  console.log("邀请码数据:", options.scene || "无邀请数据...");
      // uni.setStorageSync('scene', options.scene)
    },
    onUnload() {
      clearInterval(this.broadcastIntervalId);
    },
    methods: {
      //获取广播数据
      async getbroadcast() {
        try {
          const response = await getbroadcast();
          //  console.log("完整的响应数据:", response.data);

          // 检查 response.data 是否存在，并且 response.data.data 是否是一个数组
          if (response.data && Array.isArray(response.data.data)) {
            // 使用 map 方法提取每个元素的 content 属性
            this.broadcasts = response.data.data[0].content;
            //  console.log("提取的广播内容:", this.broadcasts);
          } else {
            console.error('获取的广播数据格式不正确', response.data);
          }
        } catch (error) {
          console.error('获取广播数据失败:', error);
        }
      },

      //获取用户信息
      getUserInfo() {
        const userInfo = uni.getStorageSync('userInfo')
        this.userId = userInfo.userId
        uni.setStorageSync('userId', this.userId)

      },
      getGoodslx() {
        getGoodslx().then(res => {
          this.categoryList = res.data.data.goodlx;
        })
      },
      goToCategory(index) {
        //  console.log(index)
        // 在跳转前保存数据到本地存储
        uni.setStorageSync('currentView', index);
        uni.switchTab({
          url: `/pages/classify/classify`
        });
      },
      goToMoreProduct() {
        uni.switchTab({
          url: '/pages/classify/classify'
        });
      },

      startBroadcast() {
        this.broadcastIntervalId = setInterval(() => {
          this.currentBroadcastIndex =
            (this.currentBroadcastIndex + 1) % this.broadcasts.length;
        }, 3000); // 每3秒切换一次广播
      },
      grade(grade) {
        switch (grade) {
          case 1:
            return "甄选";
          case 2:
            return "优选";
          case 3:
            return "一级品";
          case 4:
            return "二级品";
          case 5:
            return "三级品";
          default:
            return "";
        }
      },
      getOpenid() {
        // const openid = uni.getStorageSync("openid") || null;
        // //  console.log(openid);
        // if (openid) {
        // 	return;
        // } else {
        // 	uni.redirectTo({
        // 		url: "/pages/login/login",
        // 	});
        // }
      },
      updateCartCount() {
        const cartItems = uni.getStorageSync("cartItems") || [];
        this.cartItemCount = cartItems.length;
      },

      goToProductDetail(item) {
        //判断库存
        if (item.inventory <= 0) {
          return;
        }
        //添加历史足迹
        InsertFootPrint(this.userId, item).then(res => {
          //  console.log("插入历史足迹", res)
        }, ).catch(res => {
          //  console.log(res);
        })
        //  console.log(item);
        // 导航到商品详情页并传递所选商品信息
        uni.navigateTo({
          url: `/pages/goodDetail/goodDetail?createdAt=${
            item.createdAt
          }&deletedAt=${
            item.deletedAt
          }& goodsAdminId=${
            item.goodsAdminId
          }&goodsLxID=${
            item.goodsLxID
          }&userMoney=${
            item.userMoney
          }&updatedAt=${
            item.updatedAt
          }&state=${
            item.state
          }&id=${
               item.id
             }&goodsName=${encodeURIComponent(item.goodsName)}&money=${
               item.money
             }&image=${encodeURIComponent(item.image)}&grade=${
               item.grade
             }&details=${encodeURIComponent(item.details)}&inventory=${
               item.inventory
             }&sales=${item.sales}&`,
        });
      },
      getCarousel() {
        // 获取轮播图
        getCarousel()
          .then((res) => {
            this.swiperList = res.data.data;
          })
          .catch((res) => {
            //  console.log(res);
          });
      },
      getGoodsInfo() {
        // 获取商品列表
        getGoodsInfo()
          .then((res) => {
            //  console.log(res.data.data);
            this.productList = res.data.data;
          })
          .catch((res) => {
            //  console.log(res);
          });
      },
      addToCart(item) {
        //判断库存
        if (item.inventory <= 0) {
          return;
        }
        // 加入购物车的逻辑
        //  console.log(`${item.goodsName} 已加入购物车`);

        // 获取当前购物车中的商品
        let cartItems = uni.getStorageSync("cartItems") || [];
        // 检查购物车中是否已有该商品
        let existItem = cartItems.find((cartItem) => cartItem.id === item.id);

        if (existItem) {
          // 如果商品已存在，则增加数量
          existItem.quantity += 1;
        } else {
          // 如果商品不存在，则添加到购物车数组中
          item.quantity = 1; // 初始化数量
          cartItems.push(item);
        }

        // 更新购物车中的商品数据到本地存储
        uni.setStorageSync("cartItems", cartItems);


        uni.showToast({
          title: `加入成功`,
          icon: "success",
        });

        this.updateCartCount(); // 更新徽章
      },

      playVideo(item) {
        // 显示视频播放器
        if (!item.mp4) return;
        this.mp4Url = item.mp4;
        this.isVideoPlaying = true;
        const videoContext = uni.createVideoContext("myVideo");
        videoContext.play();
      },
      closeVideo() {
        // 关闭视频播放器
        this.isVideoPlaying = false;
      },
      onVideoEnd() {
        // 视频结束时隐藏播放器
        this.isVideoPlaying = false;
      },
      toLogin() {},
    },
  };
</script>

<style scoped>
  .body {
    padding: 0 0 50px 0;
    width: 100%;
    height: 100%;
  }

  swiper {
    height: 200px;
  }

  /* 轮播图样式 */
  .banner-item {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 200px;
    background-color: white;
    color: #333;
  }

  /* 广播样式 */
  .broadcast {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 10px 0;
  }

  .broadcast-content {
    display: flex;
    align-items: center;
    white-space: nowrap;
    animation: scroll-left 15s linear infinite;
  }

  .broadcast-image {
    width: 30px;
    height: 30px;
    margin-right: 10px;
  }

  .broadcast-text {
    font-size: 14px;
    color: #333;
  }

  /* 关键帧动画 */
  @keyframes scroll-left {
    from {
      transform: translateX(0);
    }

    to {
      transform: translateX(-100%);
    }
  }

  /* 商品列表样式 */
  .product-list {
    padding: 15px;
  }

  .product-item {
    display: flex;
    flex-direction: row;
    background-color: #fff;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    margin-bottom: 15px;
    padding: 15px;
  }

  .product-image {
    width: 100px;
    height: 100px;
    border-radius: 10px;
    margin-right: 15px;
  }

  .product-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }

  .product-title {
    margin-bottom: 5px;
  }

  .proudct-sales,
  .product-content {
    color: #999;
    margin-bottom: 10px;
  }

  .product-content {
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 隐藏溢出的内容 */
    text-overflow: ellipsis;
    /* 显示省略号 */
  }

  .price-cart {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .product-price,
  .member-price {
    font-size: 14px;
    color: #04be02;
  }

  .cart-button {
    background-color: #04be02;
    color: #fff;
    border: none;
    margin: 5px 5px;
    border-radius: 5px;
    font-size: 14px;
  }

  .disabled {
    background-color: #ccc;
    /* 禁用时的背景色 */
    cursor: not-allowed;
  }

  /* 视频播放器样式 */
  .video-container {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.8);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
  }

  .close-button {
    position: absolute;
    top: 10px;
    right: 10px;
    font-size: 24px;
    color: #fff;
    padding: 10px;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 50%;
    cursor: pointer;
  }

  .bottom-tabbar {
    position: fixed;
    width: 100%;
    height: 130rpx;
    display: flex;
    justify-content: space-around;
    align-items: center;
    bottom: 0px;
    background-color: white;
  }

  .tabbar-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .tabbar-item image {
    width: 30px;
    height: 30px;
    margin-bottom: 5px;
  }

  .tabbar-item.shoppingCart {
    position: relative;
    /* This is needed for the badge to be positioned relative to the shopping cart icon */
  }

  .price-buttom {
    display: flex;
    flex-direction: column;
  }


  /* 容器样式 */
  .category-list {
    width: 100%;
    display: flex;
    /* 开启Flex布局 */
    flex-direction: row;
    /* 子元素横向排列 */
    /* 子元素之间的间距平均分布 */
    flex-wrap: wrap;
    /* 允许子元素换行 */
    margin: 2% 0;
    justify-content: center;
    background-color: white;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  /* 每个类别项的样式 */
  .category-item {
    display: flex;
    /* 开启Flex布局 */
    flex-direction: column;
    /* 子元素纵向排列 */
    align-items: center;
    /* 子元素在交叉轴上居中对齐 */
    margin: 10px 0;
    flex-basis: 24%;
    /* 外边距 */
  }

  /* 图片样式 */
  .category-image {
    width: 55px;
    /* 图片宽度 */
    height: 55px;
    /* 图片高度 */
    object-fit: cover;
    /* 裁剪并填充整个元素 */
    border-radius: 50%;
  }

  /* 名称文本样式 */
  .category-LXName {
    text-align: center;
    /* 文本居中 */
    margin-top: 10px;
    /* 与图片的间距 */
    font-size: 14px;
  }

  .more {
    text-align: right;
    margin-right: 5%;
    font-size: 14px;
    font-weight: 700;
  }

  .product-image-wrapper {
    position: relative;
  }

  .sold-out-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 100px;
    height: 100px;
    background-color: rgba(0, 0, 0, 0.5);
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    border-radius: 8px;
    /* 与图片保持一致 */
  }
</style>